<?php

/**
 * Subclass for representing a row from the 'files' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Files extends BaseFiles
{

	public function hydrate(ResultSet $rs, $startcol = 1)
	{
		$this->setCulture(sfContext::getInstance()->getUser()->getCulture());

		parent::hydrate($rs, $startcol);
	}

	/**
	* Returns parsed file name for file deletion URL
	*/
	public function getNameforurl() 
	{
		
		$name = explode('.', $this->getUname());
		if( !$name ) 
		{
			throw new Exception();
		}
		return $name[0] . '_' . $name[1];
		//debugvar($name);
		//die();
	}

	/**
	* Returns parsed file name for object deletion method
	* @param $uname string - unique file name with '.' instead of '_'
	*/
	public static function getNameFromUrl($uname) 
	{
        //debugvar($uname,'uname');
		$arName = explode('_', $uname);
//		debugvar($arName,'arName');
		if( !$arName ) 
		{
			throw new Exception('Bad name to convert from URL (' . $uname . ')');
		}
		return $arName[0] . '.' . $arName[1];
	}

    protected static function deleteRealFile($file, $forceDeleteDb = false)
    {
        if( !empty($file) )
        {
            $dirs = sfConfig::get('app_symcms_files_galleries');
            foreach($dirs as $key => $value)
            {
                $galleryDir = $value['dir'];
                $path = sfConfig::get('sf_web_dir') . '/' . sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $galleryDir . '/';
                $filename = $path . $file->getUname();
                if( !@unlink($filename) )
                    $isOk = false;
            }
            // Delete DB record only if all files were removed
            if( $forceDeleteDb || $isOk )
                $file->delete();
        }
    }

    /**
    *   Returns the first file (by priority) for specific object (and user if is set)
    *   @param $objId integer - ID of object to count
    *   @param $objType integer type of object
    *   @param $userId integer - ID of user, who is the owner of files, optional (SHOULD NOT be 0!)
    *   @return Files object
    */
    public static function getFirst($objId, $objType, $userId = 0)
    {
        if( $userId == 0 )
        {
            throw new Exception('You need to specify ID and type of object to get its photo!');
        }
        $c = new Criteria();
        $c->add(FilesPeer::OBJ_ID, $objId);
        $c->add(FilesPeer::OBJ_TYPE, $objType);

        // If need to select only user objects
        if( $userId != MyConstants::UNDEFINED_ID )
        {
            $c->add(FilesPeer::USER_ID, $userId);
        }

        $c->addDescendingOrderByColumn(FilesPeer::PRIORITY);

        return FilesPeer::doSelectOne($c);
    }

    /**
    *   Counts files for specific object (and user if is set)
    *   @param $objId integer - ID of object to count
    *   @param $objType integer - constant of object types
    *   @param $userId integer - ID of user, who is the owner of files, optional
    *   @return integer number of files which belong to modules object
    */
    public static function countObjects($objId, $objType, $userId = 0)
    {
        $c = new Criteria();
        $c->add(FilesPeer::OBJ_ID, $objId);
        $c->add(FilesPeer::OBJ_TYPE, $objType);
        // If need to count only user objects
        if( $userId )
        {
            $c->add(FilesPeer::USER_ID, $userId);
        }

        return FilesPeer::doCount($c);
    }

    /**
    *   Returns path to image directory by its name
    *   @param $dirName string - name of directory, i.e. tiny, small, etc
    *   @param needAbsolute boolean - wheter to return full path to image
    *   @return string path to directory or empty string, i.e. uploads/gallery/tiny/
    */
    public static function getDirPath($dirName, $needAbsolute = false)
    {
        $path = '';
        $arDirs = Files::getPhotoDirs();
        //debugvar($arDirs, 'Directory of images:');
        if( !empty( $arDirs[$dirName] ) )
        {
            if( $needAbsolute )
            {
            	if(sfConfig::has('sf_web_dir'))
            	{
            		$path = sfConfig::get('sf_web_dir') . '/' . sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $arDirs[$dirName]['dir'] . '/';
            	}else
            	{
            		throw new Exception('sf_web_dir must be set in sf10/app/frontend/config/config.php!');
            	}
                
            }
            else
            {
                $path = sfConfig::get('app_symcms_files_gallery_dir') . '/' . $arDirs[$dirName]['dir'] . '/';
            }
        }

        return $path;
    }

    /**
    *   Saves uploaded file to user defined directories
    *   @param $uploadedName string - unique name (FilesPeer::UNAME) in table
    *   @param $uploadedFile string - path to file uploaded by PHP
    *   @param $objectId string - retrieved id of the object
    *   @param $userId string - id of the user which created object
    *   @param $objectType string - mime of the uploaded file
    *   @param $uploadPath array - array of upload directories retrieved from sfConfig::get('app_galleries'), by user selection
    *   @param $culture - culture code needed for saving file object into i18n table
    */
    public static function saveTo($uploadedName, $uploadedFile, $objectId, $userId, $objectType, $culture, $statusId, $fileName, $text, $uploadPath = array())
    {
        $isOk = true;
        if( $objectId && $userId && $uploadedName )
        {

            $bExt = substr($uploadedName, strrpos($uploadedName, '.') + 1);
			$ext = strtolower($bExt);
            $file = new Files();
            $file->setStatusId($statusId);
            $file->setRealName($uploadedName);
            $file->setCulture($culture);
            $file->setText($text);
            $file->setUname(md5($uploadedName . '-' . $objectId . '-' . $userId) . '.' . $ext);
            $file->setUserId($userId);
            $file->setObjType($objectType);
            $file->setName($fileName);
            $file->setObjId($objectId);
            //$file->save();

            if( count($uploadPath) < 1 )
                $imgSizes = Files::getPhotoDirs();
            else
                $imgSizes = $uploadPath;

            $thumb_type = sfConfig::get('app_symcms_files_thumb_type');
            //if ($file->getId())
            //{
                foreach( $imgSizes as $key => $value )
                {
                    $galleryDir = $value['dir'];
                    $path = Files::getDirPath($value['dir'], true);
                    if( $path == '' )
                    {
                        $path = sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $galleryDir . '/';
                    }
//                    debugvar('Save file to: ' . $path);
                    $newFile = $path . $file->getUname();
                    $type = 'image/' . $ext;
                    if (!file_exists($path))
                    {
                        @mkdir($path, 0777);
                    }
                    if( !@copy($uploadedFile, $newFile) )
                        $isOk = false;

                    $img = new sfImage($newFile, $type);
                    //Resize works when width or height is null
                    if( !$value['w'] || !$value['h'] )
                    {
                        //debugvar($value);
                        //die('aha');
                        $res = $img->resize($value['w'], $value['h']);
                    }
                    else
                        $res = $img->thumbnail($value['w'], $value['h'], $thumb_type);

                    if( $res )
                    {
                        $img->save();
                    }
                }
                @unlink($uploadedFile);
            //}

            if( $isOk )
            {
                //debugvar($file);
                //exit('saving...');
                $file->save();
            }
        }
        else
        {
//debugvar($objectId . 'obj');
//debugvar($userId . 'user'); debugvar($uploadedName . 'upload');
            die('Missing information for file upload..');
        }
    }

    /**
     * save croped files. file objects not duplicated
     * Enter description here ...
     * @param string $uploadedName
     * @param string $uploadedFile
     * @param int $objectId
     * @param int $userId
     * @param int $objectType
     * @param string $culture
     * @param int $statusId
     * @param string $fileName
     * @param string $text
     * @param array $uploadPath
     */
    public static function saveCropedTo($uploadedName, $uploadedFile, $objectId, $userId, $objectType, $culture, $statusId, $fileName, $text, $uploadPath = array())
    {
        $isOk = true;
        if( $objectId && $userId && $uploadedName )
        {

            $bExt = substr($uploadedName, strrpos($uploadedName, '.') + 1);
            $ext = strtolower($bExt);
            $file = new Files();
            $file->setStatusId($statusId);
            $file->setRealName($uploadedName);
            $file->setCulture($culture);
            $file->setText($text);
            $file->setUname(md5($uploadedName . '-' . $objectId . '-' . $userId) . '.' . $ext);
            $file->setUserId($userId);
            $file->setObjType($objectType);
            $file->setName($fileName);
            $file->setObjId($objectId);
            //$file->save();

            if( count($uploadPath) < 1 )
                $imgSizes = Files::getPhotoDirs();
            else
                $imgSizes = $uploadPath;

            $thumb_type = sfConfig::get('app_symcms_files_thumb_type');
            //if ($file->getId())
            //{
                foreach( $imgSizes as $key => $value )
                {
                    $galleryDir = $value['dir'];
                    
                    $path = Files::getDirPath($value['dir'], true);
                    if( $path == '' )
                    {
                        $path = sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $galleryDir . '/';
                    }
//                    debugvar('Save file to: ' . $path);
                    $newFile = $path . $file->getUname();
                    $type = 'image/' . $ext;
                    if (!file_exists($path))
                    {
                        @mkdir($path, 0777);
                    }
                    $cropedFile = $path . $uploadedName;
                    if( !@copy($cropedFile, $newFile) )
                        $isOk = false;

                    $img = new sfImage($newFile, $type);
                    //Resize works when width or height is null
                    if( !$value['w'] || !$value['h'] )
                    {
                        //debugvar($value);
                        //die('aha');
                        $res = $img->resize($value['w'], $value['h']);
                    }
                    else
                        $res = $img->thumbnail($value['w'], $value['h'], $thumb_type);

                    if( $res )
                    {
                        $img->save();
                    }
                    @unlink($cropedFile);
                }
            //}

            if( $isOk )
            {
                //debugvar($file);
                //exit('saving...');
                $file->save();
            }
        }
        else
        {
//debugvar($objectId . 'obj');
//debugvar($userId . 'user'); debugvar($uploadedName . 'upload');
            die('Missing information for file upload..');
        }
    }
    /**
    *   Deletes file by unique name. Does not check ownership!
    *   @param $fileName string - unique name (FilesPeer::UNAME) in table
    */
    public static function deleteByUname($fileUname, $forceDeleteDb = false, $dirs = array())
    {
        /* @var $f Files */

        // Do we delete DB record
        $isOk = true;
        $c = new Criteria();
        $c->add(FilesPeer::UNAME, $fileUname);
        $f = FilesPeer::doSelectOne($c);

        if( !empty($f) )
        {
        	if(empty($dirs))
                $dirs = sfConfig::get('app_symcms_files_galleries');
            foreach($dirs as $key => $value)
            {
                $galleryDir = $value['dir'];
                // TODO: full path to image!
                $path = sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $galleryDir . '/';
                //debugvar($path);
//                $file = Files::getDirPath($value['dir'], true) . $f->getUname();
                $file = $path . $f->getUname();
                if( !@unlink($file) )
                {
                    $isOk = false;
                }
            }
            if( $forceDeleteDb || $isOk )
            {
                $f->delete();
            }
        }

    }

    /**
    *   Retrieves array of files that have common object IDs
    *   @param $objId integer - object id (FilesPeer::OBJ_ID) in table
    *   @param $userId integer - ID of user to extract, could be 0 for any user
    */
    public static function getByObj($objType, $objId, $userId = 0)
    {
        $c = new Criteria();
        $c->add(FilesPeer::OBJ_TYPE, $objType);
        $c->add(FilesPeer::OBJ_ID, $objId);
        if( $userId > 0 )
        {
            $c->add(FilesPeer::USER_ID, $userId);
        }

        $c->addDescendingOrderByColumn(FilesPeer::PRIORITY);
        $f = FilesPeer::doSelect($c);

        if( !empty($f) )
        {
            return $f;
        }
        return array();
    }

    /**
    *
    *
    */
    public static function getPhotoDirs()
    {
        $allDirs = sfConfig::get('app_symcms_files_galleries');
        if(empty($allDirs))
        {
            $allDirs = array();
        }
        return $allDirs;
    }

    /**
    *   Deletes file by object ID. Does not check ownership!
    *   @param integer $objId - object ID (FilesPeer::OBJ_ID) in table
    */
    public static function deleteByObjId($objId, $forceDeleteDb = false, $objType = null)
    {
        // Do we delete DB record
        $isOk = true;
        $c = new Criteria();
        $c->add(FilesPeer::OBJ_ID, $objId);
		
		if(isset($objType))
		{
			$c->add(FilesPeer::OBJ_TYPE, $objType);
		}

        $f = FilesPeer::doSelect($c);
        foreach( $f as $file )
        {
            self::deleteRealFile($file, $forceDeleteDb);
        }

    }
    
    /**
     * 
     * saves and rotetes
     * @param $uploadedName
     * @param $uploadedFile
     * @param $objectId
     * @param $userId
     * @param $objectType
     * @param $culture
     * @param $statusId
     * @param $fileName
     * @param $text
     * @param $uploadPath
     */
    public static function saveRotate($uploadedName, $uploadedFile, $objectId, $userId, $objectType, $culture, $statusId, $fileName, $text, $uploadPath = array())
    {
        $isOk = true;
        if( $objectId && $userId && $uploadedName )
        {

            $bExt = substr($uploadedName, strrpos($uploadedName, '.') + 1);
            $ext = strtolower($bExt);
            $file = new Files();
            $file->setStatusId($statusId);
            $file->setRealName($uploadedName);
            $file->setCulture($culture);
            $file->setText($text);
            $file->setUname(md5($uploadedName . '-' . $objectId . '-' . $userId) . '.' . $ext);
            $file->setUserId($userId);
            $file->setObjType($objectType);
            $file->setName($fileName);
            $file->setObjId($objectId);
            //$file->save();

            if( count($uploadPath) < 1 )
                $imgSizes = Files::getPhotoDirs();
            else
                $imgSizes = $uploadPath;

            $thumb_type = sfConfig::get('app_symcms_files_thumb_type');
            //if ($file->getId())
            //{
                foreach( $imgSizes as $key => $value )
                {
                    $galleryDir = $value['dir'];
                    $path = Files::getDirPath($value['dir'], true);
                    if( $path == '' )
                    {
                        $path = sfConfig::get('app_symcms_files_images_dir') . '/' . sfConfig::get('app_symcms_files_gallery_dir') . '/' . $galleryDir . '/';
                    }
//                    debugvar('Save file to: ' . $path);
                    $newFile = $path . $file->getUname();
                    $type = 'image/' . $ext;
                    if (!file_exists($path))
                    {
                        @mkdir($path, 0777);
                    }
                    if( !@copy($uploadedFile, $newFile) )
                        $isOk = false;
                    //switch($ext)
                    //{
                    //    case 'jpg':
                    //        $sorce = imagecreatefromjpeg($newFile);
                    //        $sorce = imagerotate( $sorce, 15, 13421515 );
                    //        imagejpeg($sorce, $newFile);
                    //        break;
                    //    case 'png':
                     //       $sorce = imagecreatefrompng($newFile);
                    //        $sorce = imagerotate( $sorce, 15, 5029452 );
                    //        imagepng($sorce, $newFile);
                    //        break;
                   // }
                    $img = new sfImage($newFile, $type);
                    //Resize works when width or height is null
                    if( !$value['w'] || !$value['h'] )
                    {
                        //debugvar($value);
                        //die('aha');
                        $res = $img->resize($value['w'], $value['h']);
                    }
                    else
                        $res = $img->thumbnail($value['w'], $value['h'], $thumb_type);

                    if( $res )
                    {
                        $img->save();
                    }
                }
                @unlink($uploadedFile);
            //}

            if( $isOk )
            {
                //debugvar($file);
                //exit('saving...');
                $file->save();
            }
        }
        else
        {
//debugvar($objectId . 'obj');
//debugvar($userId . 'user'); debugvar($uploadedName . 'upload');
            die('Missing information for file upload..');
        }
    }

}
